import { PostService } from './post.service';
import {
  Body,
  Controller,
  Delete,
  Get,
  Post,
  Put,
  Query,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';

import { ApiResult } from '~/common/decorators/api-result.decorator';
import { IdParam } from '~/common/decorators/id-param.decorator';
import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator';
import { BusinessException } from '~/common/exceptions/biz.exception';
import { CreatorPipe } from '~/common/pipes/creator.pipe';
import { UpdaterPipe } from '~/common/pipes/updater.pipe';
import { ErrorEnum } from '~/constants/error-code.constant';
import { AuthUser } from '~/modules/auth/decorators/auth-user.decorator';
import {
  definePermission,
  Perm,
} from '~/modules/auth/decorators/permission.decorator';
import { PostEntity } from '~/modules/system/post/post.entity';
import { Pagination } from '~/helper/paginate/pagination';

import { PostDto, PostQueryDto } from './post.dto';

export const permissions = definePermission('system:post', {
  LIST: 'list',
  CREATE: 'create',
  READ: 'read',
  UPDATE: 'update',
  DELETE: 'delete',
} as const);

@ApiSecurityAuth()
@ApiTags('System - 岗位模块')
@Controller('post')
export class PostController {
  constructor(private readonly postService: PostService) {}

  @Get()
  @ApiOperation({ summary: '获取岗位列表' })
  @ApiResult({ type: [PostEntity], isPage: true })
  @Perm(permissions.LIST)
  async list(@Query() dto: PostQueryDto) {
    return this.postService.list(dto);
  }

  @Post()
  @ApiOperation({ summary: '创建岗位' })
  @Perm(permissions.CREATE)
  async create(@Body(CreatorPipe) dto: PostDto): Promise<void> {
    await this.postService.create(dto);
  }

  @Get(':id')
  @ApiOperation({ summary: '查询岗位信息' })
  @Perm(permissions.READ)
  async info(@IdParam() id: number) {
    return this.postService.info(id);
  }

  @Put(':id')
  @ApiOperation({ summary: '更新岗位' })
  @Perm(permissions.UPDATE)
  async update(
    @IdParam() id: number,
    @Body(UpdaterPipe) updatePostDto: PostDto
  ): Promise<void> {
    await this.postService.update(id, updatePostDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除岗位' })
  @Perm(permissions.DELETE)
  async delete(@IdParam() id: number): Promise<void> {
    // 查询是否有关联用户或者岗位，如果含有则无法删除
    const isExist = await this.postService.checkUserByPostId(id);
    if (isExist)
      throw new BusinessException(ErrorEnum.POST_HAS_ASSOCIATED_USERS);

    await this.postService.delete(id);
  }
}
